#include "window.h"

#include "UrdfWidget.h"
#include "webrtc/webrtcwidget.h"

#include <QTime>

#include <QRandomGenerator>
#include<QDebug>
#include <mainwindow.h>
#include <slamwidget.h>

Window::Window(WindowType type, QWidget *parent, int nID, QString strName,QString strUrl):
    QWidget(parent),
    m_nType(type),
    m_nID(nID),
    m_strName(strName),
    m_pWidget(NULL)
{
    setAttribute(Qt::WA_StyledBackground, true);

    setStyleSheet("QWidget{background-color:black;"
                  "border: 1px solid  #48494E;}");
    switch(type)
    {
    case Window_Video:
        m_pWidget =  MainWindow::getInstance()->pVideoWidget(strUrl);
        break;
    case Window_Urdf:
        m_pWidget = MainWindow::getInstance()->pUrdfWidget();
        break;
    case Window_Slam:
        m_pWidget = MainWindow::getInstance()->pMapWidget();
        break;
    }
    m_pCloseBtn  = new TouchButton(this);
    m_pCloseBtn->setStyleSheet("QPushButton{ \
        border-image: url(:/images/delete.png); \
        background-color:transparent; \
        border: 0px \
        } \
        QPushButton:pressed{ \
        background-color: rgb(255, 0, 0); \
        }");

    connect(m_pCloseBtn, &QPushButton::clicked, this, [&](){emit closeClicked(this);});
}

Window::~Window()
{
    //不要讓窗口被delete
    if(m_pWidget)
    m_pWidget->setParent(NULL);
}

int Window::nID() const
{
    return m_nID;
}

QString Window::strName() const
{
    return m_strName;
}

void Window::setBMax(bool newBMax)
{
    m_bMax = newBMax;
    if(!m_pWidget)
        return;
    if(m_nType == Window_Video)
    {
        ((VideoBase *)m_pWidget)->setShowMax(m_bMax);
    }
    else if(m_nType == Window_Slam )
    {
        ((SlamWidget *)m_pWidget)->setShowMax(m_bMax);
    }
    if(m_bMax)
    {
        m_pCloseBtn->hide();
        if(m_pWidget)
        {
            m_pWidget->setGeometry(0,0,width(),height());
        }
    }
    else
    {
        m_pCloseBtn->show();
        if(m_pWidget)
            m_pWidget->setGeometry(1,1,width()-2,height()-2);
    }
}

void Window::mousePressEvent(QMouseEvent *event)
{
    QWidget::mousePressEvent(event);
    emit windowClicked(this);
}

void Window::resizeEvent(QResizeEvent *event)
{
    Q_UNUSED(event);
    m_pCloseBtn->setGeometry(width()-int(40*g_xScale),0,int(40*g_xScale),int(40*g_xScale));
}

void Window::showEvent(QShowEvent *event)
{
    Q_UNUSED(event);
    if(m_pWidget)
    {
        m_pWidget->setParent(this);
        m_pWidget->show();
        if(m_bMax)
        {
            m_pWidget->setGeometry(0,0,width(),height());
        }
        else
        {
            m_pWidget->setGeometry(1,1,width()-2,height()-2);
            m_pCloseBtn->show();
        }
        if(m_nType == Window_Video)
        {
            ((VideoBase *)m_pWidget)->setShowMax(m_bMax);
        }
        else if(m_nType == Window_Slam )
        {
            ((SlamWidget *)m_pWidget)->setShowMax(m_bMax);
        }
        m_pCloseBtn->raise();
    }
}
